using System;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.IO;

namespace OpenWaves.EPiServer.AdminTools.LogViewer
{
    public class LogFile
    {
        private readonly string path;
        private readonly FileInfo fileInfo;

        public LogFile(string path)
        {
            Contract.Requires<ArgumentNullException>(String.IsNullOrEmpty(path) == false);

            this.path = path;
            this.fileInfo = new FileInfo(this.path);
        }

        public string Name
        {
            get { return System.IO.Path.GetFileName(path); }
        }

        public string Path
        {
            get { return path; }
        }

        public string GetContent(BinaryUnit maxLength)
        {
            using (var fs = File.Open(this.path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                if (maxLength < this.Size)
                {
                    fs.Seek(-1*maxLength, SeekOrigin.End);
                }
                
                using (var sr = new StreamReader(fs))
                {
                    return sr.ReadToEnd();
                }
            }
        }

        public DateTime LastModified
        {
            get { return fileInfo.LastWriteTime; }
        }

        public BinaryUnit Size
        {
            get { return BinaryUnit.FromBytes(fileInfo.Length); }
        }
    }
}